package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.GlobalExceptionHandle;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.time.LocalDateTime;


/**
 * @email 1572178030@qq.com
 * @author:黄海宾
 * @date: 2023/2/5  18:53
 */

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("login=================");
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(employee.getUsername() != null, Employee::getUsername, employee.getUsername());

        Employee emp = employeeService.getOne(queryWrapper);

        if (emp == null) {
            return R.error("登录失败");
        }

        if (!emp.getPassword().equals(password)) {
            return R.error("登录失败");
        }
        if (emp.getStatus() == 0) {
            return R.error("已禁用该用户");
        }
        request.getSession().setAttribute("employee", emp.getId());
        System.out.println("==================");
        return R.success(emp);
    }


    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {

        request.getSession().removeAttribute("employee");
        return R.success("success");

    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        //获得密码进行加密，存入数据库中

        String password = DigestUtils.md5DigestAsHex("123456".getBytes());

        //设置日期，作者
       // employee.setCreateTime(LocalDateTime.now());
       // employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long) request.getSession().getAttribute("employee");
       // employee.setCreateUser(empId);
       // employee.setUpdateUser(empId);


        //设置密码
        employee.setPassword(password);
        System.out.println(employee);
        //保存到数据库中,名字设置了唯一性
        try {
            employeeService.save(employee);
        } catch (Exception e) {
            e.printStackTrace();

            return R.error("新增员工失败");
        }


        return R.success("新增员工成功");
    }

    /**
     * 员工信息分页查询
     *
     * @param page     当前查询页码
     * @param pageSize 每页展示记录数
     * @param name     员工姓名 - 可选参数
     * @return 在看看
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("员工分页查询接口");
        Page employeePage = new Page(page, pageSize);

        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        //根据时间排序
        wrapper.orderByDesc(Employee::getUpdateTime);

        Page pageCondition = employeeService.page(employeePage, wrapper);
        return R.success(pageCondition);

    }

    /**
     * 根据id修改员工信息
     * 员工的禁用和启用
     * @param employee
     * @return
     */

    @PutMapping
    public R<String> statusEmploy(HttpServletRequest request, @RequestBody Employee employee) {
        //employee 中status的状态被前端改了传过来了
        //employee.setUpdateTime(LocalDateTime.now());
        Long empId = (Long) request.getSession().getAttribute("employee");
       // employee.setUpdateUser(empId);
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> editEmployee(@PathVariable Long id){
        log.info("查询id");

        Employee employee = employeeService.getById(id);
        if (employee !=null){
            return R.success(employee);
        }
      return R.error("没有查询到对应员工信息");
    }


}
